import { CzmES3DTileset } from "@czmSrc/CzmObjects";
import { ES3DTileset, ESJResource, ESSceneObject } from "earthsdk3";
import * as Cesium from 'cesium';
export function getCzmCodeFromES3DTileset(eS3DTileset: ES3DTileset) {
    if (!eS3DTileset.url) return undefined;
    const finalUrl = getFinalCzm3DTilesUrlString(eS3DTileset.url);
    const czmES3DTileset = eS3DTileset.viewer?.getEngineObject(eS3DTileset) as CzmES3DTileset;
    const modelMatrix = czmES3DTileset.czm3DTiles.tileset?.modelMatrix ?? Cesium.Matrix4.IDENTITY;
    const modelMatrixArr = Cesium.Matrix4.toArray(modelMatrix);
    return /*js*/`\
        (async function () {
            var tileset = await Cesium.Cesium3DTileset.fromUrl(
                ${finalUrl},
            );
            tileset.modelMatrix = Cesium.Matrix4.fromArray([${modelMatrixArr}]);
            viewer.scene.primitives.add(tileset);
            viewer.flyTo(tileset);
            return tileset;
        })();`;
}
export function getFinalCzm3DTilesUrlString(czm3DTilesUrl: string | ESJResource) {
    let finalUrl;
    let url = typeof czm3DTilesUrl == 'string' ? czm3DTilesUrl : czm3DTilesUrl.url;
    do {
        if (!url.startsWith('Ion(')) break;
        let rr = /Ion\((\d+)/.exec(url);
        if (!rr) break;
        let assetId = rr[1] && +rr[1];
        try {
            assetId && (finalUrl = `"await Cesium.IonResource.fromAssetId(${assetId}))"`);
        } catch (error) {
            console.error(`Ion资源未能获取到 error: ${error}`, error);
            break;
        }
    } while (false);
    finalUrl = finalUrl || `"${ESSceneObject.context.getStrFromEnv(url)}"`;
    return finalUrl;
}